/**
 * 封装sendRequest请求
 * @param {Object} url	请求路径
 * @param {Object} data	请求参数	
 * @param {Object} method	请求方法默认为POST
 * @param {Object} header	头部信息默认为application/x-www-form-urlencoded;charset=UTF-8
 */
import config from './config.js'
const SendUrl = config.Url

function sendRequest(url, param, method = "POST", header = "application/x-www-form-urlencoded;charset=UTF-8") {
	uni.showLoading({
		title: '加载中...',
	})
	// 网络无网时候
	uni.onNetworkStatusChange(function(res) {
		if (!res.isConnected) {
			uni.reLaunch({
				url: '../NoServer/NoServer'
			})
		}
	});
	// param.userId = uni.getStorageSync("userId") || '8880202106210000028'
	// console.log('88802021062100000288880202106210000028',param)
	// console.log("paramparamparamparam",param)
	return new Promise(function(resolve, reject) {
		const access_token = uni.getStorageSync("token")
		console.log('access_tokenaccess_token', access_token)
		uni.request({
			// url: SendUrl + url + '&access_token=' + '0cH25Jo2m6cJqlCuTbRM',
			url: SendUrl + url + '&access_token=' +  access_token ||'0cH25Jo2m6cJqlCuTbRM',
			data: param,
			method: method,
			header: {
				'content-type': header,
				'access_token': access_token
			},
			success: (res) => {
				uni.hideLoading();
				const nowTiem = Date.parse(new Date())
				const serverTime = res.header['server-time']
				const difTime = Number(serverTime) - Number(nowTiem)
				uni.setStorageSync('difTime', difTime)
				console.log('1111', difTime, serverTime, nowTiem, Date.parse(new Date()))
				if (res.data.code == 200 || res.data.code == 0) {
					resolve(res);
				} else {
					if (res.data.msg != '' && res.data.msg != undefined) {
						if (res.data.msg == '余额不足，请先充值') {

						} else {
							uni.showToast({
								title: res.data.msg,
								mask: true,
								icon: "none",
								duration: 1000
							})
						}

					}
					resolve(res);
				}
			},
			fail: (err) => {
				// console.log('123', err)
				uni.hideLoading();
				reject(err)
			},
			complete(res) {
				console.log("wwww", res.header)
			}
		})
	})

}

export default {
	sendRequest
}